using System;
using System.Data;
using System.Configuration;
using System.Collections;

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using SqlWebAdmin.CSharp;
using System.Text;


public partial class TasksBox : System.Web.UI.UserControl
{

    private bool collapsed;
	protected string collapseButtonImageUrl = "~/App_Themes/default/images/icons/16/chevron_drk_up_16.gif";
    protected string expandButtonImageUrl = "~/App_Themes/default/images/icons/16/chevron_drk_down_16.gif";
    private string title = "Undefined";
	private SortedList usedSiteMapNodes = new SortedList();

    public bool IsCollapsed
    {
        get 
        {
            if (ViewState["TasksBoxCollapsed"] == null)
            {
                ViewState["TasksBoxCollapsed"] = !BoxContent.Visible;
            }

            return (bool)ViewState["TasksBoxCollapsed"];
        }
        set
        {
            ViewState["TasksBoxCollapsed"] = value;
        }
    }

    public string CollapseButtonImageUrl
    {
        get { return ResolveUrl(this.collapseButtonImageUrl); }
        set { this.collapseButtonImageUrl = value; }
    }

    public string ExpandButtonImageUrl
    {
        get { return ResolveUrl(this.expandButtonImageUrl); }
        set { this.expandButtonImageUrl = value; }
    }

    public string Title
    {
        get { return this.title; }
        set { this.title = value; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {

        this.TitleLiteral.Text = Title;

        //this.CollapseExpandButton.Click += new ImageClickEventHandler(CollapseExpandButton_Click);
        //this.CollapseExpandButton.ImageUrl = (IsCollapsed) ? expandButtonImageUrl : collapseButtonImageUrl;     
		 
		RenderContents();
		RenderBaseNodes();
        this.BoxContent.Visible = !IsCollapsed;
     
    }
	private void RenderBaseNodes()
	{
		SiteMapNode current = SiteMap.CurrentNode;
		SiteMapNodeCollection baseNodeCollection = null;
		System.Collections.SortedList sorted = new System.Collections.SortedList();
		string baseNode = current["baseNode"];
		string parentBaseNode = string.Empty;
		//if( == "true")
		BaseNodePanel.Visible = false;
		BaseNodePanel.CssClass = "taskBox_baseNodePanel";

		this.BaseNodeLabel.Text = Resources.LocalizedText.TaskBox_Additional;
		this.BaseNodeLabel.CssClass = "taskBoxLabel";

		while(parentBaseNode != "true")
		{
			if(current.ParentNode != null)
			{
			current = current.ParentNode;
			baseNode = current["baseNode"];
			parentBaseNode = baseNode;
			}
			else
				break;
		}
		
		// first add the current node.  
		// we definitely need to do this maybe
		string currentShowAsTask = current["showAsTask"];
		if (string.IsNullOrEmpty(currentShowAsTask) == false)
		{
			if (currentShowAsTask.Equals("true") || currentShowAsTask.Equals("1"))
			{
				if(Common.UserHasAccess(current))
					sorted.Add(current.Title, BuildUrl(current));
			}
		}

		if (baseNode != "true")
			return; //throw new ApplicationException("Cannot populate basenodes: The Sitemap Must have at least one basenode");

		baseNodeCollection = SiteMap.Provider.GetChildNodes(current);

		SiteMapNode node = null;

		    for(int i = 0; i < baseNodeCollection.Count; i++)
			{
				node = baseNodeCollection[i];
				
				string showTask = node["showAsTask"];
				if (!string.IsNullOrEmpty(showTask))
				{
					if (showTask.Equals("true") || showTask.Equals("1"))
					{

						string url = BuildUrl(node);

						if (url != current.Url)
						{
							if (Common.UserHasAccess(node))
								sorted.Add(node.Title, url);
						}
					}
				}
			}

			string folderImageUrl = string.Empty;
			int renderedNodes = 0;
			foreach (System.Collections.DictionaryEntry entry in sorted)
			{
				Literal item = new Literal();

				if (usedSiteMapNodes[entry.Key] == null)
				{
					renderedNodes++;
					// TODO Update folder icon to use themed icon
					//\"/SqlWebAdminCS/App_Themes/default/images/icons/16/folderclosed_16.gif\
					folderImageUrl = ResolveUrl("~/App_Themes/default/images/icons/16/folderclosed_16.gif");
					item.Text = string.Format("<div class=\"" + "boxitem\"><img src=\"" + folderImageUrl + "\">&nbsp;&nbsp;<a class=\"tabLink\" href=\"{0}\">{1}</a></div>", entry.Value, entry.Key);

					BaseNodes.Controls.Add(item);
				}
			}

			if(renderedNodes > 0)
				BaseNodePanel.Visible = true;

	}
    private void RenderContents()
    {
		CurrentNodeLabel.Text = "";
		CurrentNodePanel.Visible = false;
        SiteMapNode current = SiteMap.CurrentNode;
        System.Collections.SortedList sorted = new System.Collections.SortedList();

		SiteMapNode currentNode = current;
        if (current == null) return;

	        // Handle the current node.
        string showTask = current["showAsTask"];
		if (!string.IsNullOrEmpty(showTask))
		{
			if (showTask.Equals("true") || showTask.Equals("1"))
			{
				string queryStringKeys = current["queryStringKeys"];
				string url = current.Url;
				if (!String.IsNullOrEmpty(queryStringKeys))
				{
					string[] keys = queryStringKeys.Split(',');

					System.Collections.Specialized.NameValueCollection nvc = CollectQueryString(keys);

					url = BuildUrl(url, nvc);
				}

				if (Common.UserHasAccess(current))
					sorted.Add(current.Title, url);
			}
		}

	//	SiteMapNodeCollection smnc = SiteMap.Provider.GetChildNodes(current);
		//SiteMapNodeCollection smnc = current.GetAllNodes();
        // Build out the child nodes.
		foreach (SiteMapNode child in current.ChildNodes)
        {
	//		if (child.ParentNode == current)
			{
				string showAsTask = child["showAsTask"];
				if (!String.IsNullOrEmpty(showAsTask))
				{
					if (showAsTask.Equals("true") || showAsTask.Equals("1"))
					{
							string queryStringKeys = child["queryStringKeys"];
							string url = child.Url;
							if (!String.IsNullOrEmpty(queryStringKeys))
							{
								string[] keys = queryStringKeys.Split(',');

								System.Collections.Specialized.NameValueCollection nvc = CollectQueryString(keys);

								url = BuildUrl(url, nvc);

							}

						if (url != currentNode.Url)
						{
							
							if (Common.UserHasAccess(child))
								sorted.Add(child.Title, url);
						}
					}
				}
			}
        }

 
		if (sorted.Count > 0)
			CurrentNodePanel.Visible = true;

		string folderImageUrl = string.Empty;
        foreach (System.Collections.DictionaryEntry entry in sorted)
        {
            Literal item = new Literal();

            // TODO Update folder icon to use themed icon
			//\"/SqlWebAdminCS/App_Themes/default/images/icons/16/folderclosed_16.gif\
			folderImageUrl = ResolveUrl("~/App_Themes/default/images/icons/16/folderclosed_16.gif");
            item.Text = string.Format("<div class=\"" + (entry.Key.ToString() == SiteMap.CurrentNode.Title ? "current" : "") + "boxitem\"><img src=\"" + folderImageUrl + "\">&nbsp;&nbsp;<a class=\"tabLink\" href=\"{0}\">{1}</a></div>", entry.Value, entry.Key);

            BoxContent.Controls.Add(item);
        }

		this.usedSiteMapNodes = sorted;
    }

    private System.Collections.Specialized.NameValueCollection CollectQueryString(string[] keys)
    {
        System.Collections.Specialized.NameValueCollection nvc = new System.Collections.Specialized.NameValueCollection();
        foreach (string key in keys)
        {
            if (this.Context.Session[key] != null)
            {
                nvc.Add(key, (string)this.Context.Session[key]);
            }
            else if (!String.IsNullOrEmpty(this.Context.Request.QueryString[key]))
            {
                nvc.Add(key, this.Context.Request.QueryString[key]);
            }
        }

        return nvc;
    }

	private string BuildUrl(SiteMapNode node)
	{
		string queryStringKeys = node["queryStringKeys"];
		string url = node.Url;
		if (!String.IsNullOrEmpty(queryStringKeys))
		{
			string[] keys = queryStringKeys.Split(',');

			System.Collections.Specialized.NameValueCollection nvc = CollectQueryString(keys);

			url = BuildUrl(url, nvc);
		}
		return url;

	}

    private string BuildUrl(string baseUrl, System.Collections.Specialized.NameValueCollection nvc)
    {

        if (nvc.Count > 0)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            string seperator = baseUrl.Contains("?") ? "&" : "?";
            foreach (string key in nvc.AllKeys)
            {
                if (!baseUrl.Contains(key + "="))
                {
                    sb.AppendFormat("{0}{1}={2}", seperator, key, nvc[key]);
                    seperator = "&";
                }
            }
            baseUrl += sb.ToString();
        }

        return baseUrl;
    }

    //protected void CollapseExpandButton_Click(object sender, ImageClickEventArgs e)
    //{

    //    IsCollapsed = !IsCollapsed;
    //    this.CollapseExpandButton.ImageUrl = (IsCollapsed) ? expandButtonImageUrl : collapseButtonImageUrl;
    //    this.BoxContent.Visible = !IsCollapsed;

    //}
}
